<template>
  <div
      class="turnover-detail route-page"
      :class="$store.getters.isMobile ? 'back-class' : ''"
  >
    <section class="header">
      <a-page-header
          title="收支流水详情"
          :class="isDrawer ? 'hide-back' : ''"
          @back="goBack"
      >
        <template #tags>
          <a-space>
            <a-tag color="blue">
              {{ detail.match_status_txt }}
            </a-tag>
            <a-tag
                :color="detail.is_close == 0 ? 'red' : (detail.is_close == 1 ? 'green' : (detail.is_close == 2 ? 'cyan' : 'pink'))">
              {{
                detail.is_close == 0 ? '关闭' : (detail.is_close == 1 ? '开启' : (detail.is_close == 2 ? '审批中' : '拒绝'))
              }}
            </a-tag>
          </a-space>
        </template>
        <template #extra>
          <a-space>
            <a-button
                key="Invoicing"
                type="primary"
                ghost
                @click="makeInvoice"
                v-if="invoice_open == 1 && detail.loan_type == 'INCOME'"
            >
              <template #icon>
                <PlusOutlined/>
              </template>
              开具发票
            </a-button>
            <a-button
                key="Invoicing"
                type="primary"
                ghost
                v-if="
                  (detail.match_status == 1 || detail.match_status == 3) &&
                  detail.loan_type == 'INCOME' && 
                  detail.match_price > receiptAmountAll
                "
                @click="issueReceipts"
            >
              <template #icon>
                <PlusOutlined/>
              </template>
              开具收据 
            </a-button>
            <a-button
                key="Invoicing"
                type="primary"
                ghost
                v-if="
                  (detail.match_status == 1 || detail.match_status == 3) &&
                  detail.loan_type == 'INCOME' &&
                  detail.receipt_no
                "
                @click="viewReceipt"
            >
              查看收据
            </a-button>

            <div v-if="detail.operateButton && detail.operateButton.length">
              <a-button
                  v-if="detail.operateButton.includes('refundRevoke')"
                  @click="refundCancel"
                  style="margin-right: 8px"
              >
                撤销退款审批
              </a-button>
              <a-button
                  v-if="detail.operateButton.includes('refund')"
                  danger
                  @click="refund()"
                  style="margin-right: 8px"
              >
                退款
                <text-tip
                    :tips="['非线上支付流水退款会自动生成待退款收款账单，可匹配支出流水或结转至其它账单']"
                />
              </a-button>
              <a-button
                  v-if="detail.approval_cancel == 1"
                  @click="revokes"
                  style="margin-right: 8px"
                  v-permission="['streamList', 'auth', 'deleteStatement']"
              >
                撤销审批
              </a-button>

              <a-tooltip>
                <template #title>
                  删除流水后并且审批同意后，将不会展示在列表中，也不能重新开启流水。
                </template>
                <a-button
                    v-if="
                    detail.approval_status == 0 &&
                    detail.is_confirm != 2 &&
                    detail.match_status == 2
                  "
                    type="primary"
                    danger
                    @click="deketed()"
                    style="margin-right: 8px"
                    v-permission="['streamList', 'auth', 'deleteStatement']"
                >
                  <QuestionCircleOutlined/>
                  删除流水
                </a-button>
              </a-tooltip>

              <a-tooltip>
                <template #title v-if="detail?.is_confirm == 2">{{
                    detail?.is_confirm == 2 ? "已确定的流水不可关闭" : ""
                  }}
                </template>
                <a-button
                    danger
                    key="close"
                    v-if="detail.operateButton.includes('close')"
                    :disabled="detail?.is_confirm == 2"
                    @click="handleTopBtnClick('close')"
                    v-permission="['streamList', 'auth', 'closeStream']"
                >
                  关闭流水
                </a-button>
              </a-tooltip>

              <a-button
                  key="chargeFees"
                  type="primary"
                  v-if="detail.operateButton.includes('open')"
                  @click="handleTopBtnClick('open')"
                  v-permission="['streamList', 'auth', 'openStream']"
              >
                开启流水
              </a-button>
            </div>
          </a-space>
        </template>
      </a-page-header>
      <div class="header-extra" v-if="Object.keys(detail).length">
        <a-row
            class="owner-info"
            :class="$store.getters.isMobile ? 'owner-padding' : ''"
        >对方单位名称： {{ detail.company_name }}
        </a-row
        >
        <a-row
            class="stais-info"
            :class="$store.getters.isMobile ? 'stais-padding' : ''"
            :gutter="[12, 12]"
        >
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-statistic title="总金额（元）" :value="detail.amount"/>
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-statistic
                title="已匹配金额（元）"
                :value="detail.match_price || 0"
            />
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4">
            <a-statistic
                title="未匹配金额（元）"
                :value="detail.nomatch_price || 0"
            />
          </a-col>
          <a-col :span="$store.getters.isMobile ? 12 : 4" v-if="Number(detail.refund_price)">
            <a-statistic
                title="退款金额（元）"
                :value="detail.refund_price || 0"
            />
          </a-col>
        </a-row>
      </div>
    </section>
    <a-row>
      <a-col :span="24" style="padding:10px 12px 0px">
        <a-card :bodyStyle="{
          padding: '0'
          }">
          <a-tabs v-model:activeKey="activeKey"  @change="scrollToAnchor">
            <a-tab-pane v-for="item in tabList" :key="item.key" :tab="item.title" />
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
    <section class="content" ref="contentRef"  @scroll="handleScroll">
      <a-card title="流水信息" id="flowInfoTurnover">
        <a-descriptions
            :column="descCols"
            layout="vertical"
            :labelStyle="labelStyle"
            :contentStyle="contentStyle"
        >
          <a-descriptions-item label="借贷标">
            {{ detail.loan_type_txt || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="发生额">
            {{ detail.amount || "--" }}元
          </a-descriptions-item>
          <a-descriptions-item label="入账日期">
            {{ detail.income_date || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="对方单位名称">
            {{ detail.company_name || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="付款公司">
            {{ detail.invoice_title_txt || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="汇款方式">
            {{ detail.remit_type_txt || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="对方账号">
            {{ detail.other_account || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="凭证号">
            {{ detail.voucher_no || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="收据编号">
            {{ detail.receipt_no || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="联系人">
            {{ detail.lin_name || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="流水账户">
            <span>{{ detail.branch_name || "--" }}</span>
            <span>/</span>
            <span>{{ detail.account_name || "--" }}</span>
          </a-descriptions-item>
          <a-descriptions-item label="子账户名称">
            {{ detail.son_account_name || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="子账户">
            {{ detail.son_account || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="摘要">
            {{ detail.abstract || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="备注">
            {{ detail.remark || "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="专项预存">
            <span v-if="detail.single_type_txt">专项-</span
            >{{ detail.single_type_txt || "--" }}
          </a-descriptions-item>
          <template v-if="detail.is_close == 0">
            <a-descriptions-item
                label="关闭日期"
                v-if="detail.cancel_match_date"
            >
              {{ detail.cancel_match_date }}
            </a-descriptions-item>
            <a-descriptions-item label="关闭原因" v-if="detail.close_reason">
              {{ detail.close_reason }}
            </a-descriptions-item>
          </template>
        </a-descriptions>
      </a-card>

      <a-card title="匹配账单" class="mt-10" id="matchBillTurnover">
        <template #extra>
          <a-space>
            <a-checkbox
                v-model:checked="showCanceledBill"
                @change="handleBillCancelShowChange"
            >
              显示取消匹配账单
            </a-checkbox>
            <a-button v-if="!Pending_approval" @click="billMatchVisible = true"
                      :disabled="matchDisabled" v-permission="['streamList', 'auth', 'matchBill']">
              匹配
            </a-button>
            <a-tooltip placement="topRight">
              <template #title>匹配流水审批中暂不不可操作匹配</template>
              <a-button v-if="Pending_approval" disabled
                        v-permission="['streamList', 'auth', 'matchBill']">
                匹配
              </a-button>
            </a-tooltip>
          </a-space>
        </template>
        <a-table
            :dataSource="billList"
            :columns="BILL_LIST_COLUMNS"
            :pagination="billPagination"
            :customRow="customBillRow"
            @change="handleBillTableChange"
            rowKey="id"
        >
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'price'">
              <span>{{ text }}元</span>
            </template>
            <template v-if="column.key === 'date'">
              <span>{{ text || "--" }} </span>
            </template>
            <template v-if="column.key === 'period'">
              <span
              >{{ record.bill_start_date }} ~ {{ record.bill_end_date }}</span
              >
            </template>
            <template v-if="column.key === 'action'">
              <a-tooltip
                  v-if="
                  record.match_status == 1 ||
                  record.match_status == 3 ||
                  record.is_confirm == 2
                "
              >
                <template #title>{{
                    record?.is_confirm == 2
                        ? "流水已确认，不可取消匹配"
                        : "取消匹配"
                  }}
                </template>
                <a-button
                    type="link"
                    danger
                    :disabled="record?.is_confirm == 2"
                    @click.stop="handleBillMatchCancel(record)"
                >
                  <template #icon>
                    <DisconnectOutlined/>
                  </template>
                </a-button>
              </a-tooltip>
              <span v-else>--</span>
            </template>
          </template>
        </a-table>
      </a-card>
      <a-row class="mt-10"  id="attachmentInfoTurnover">
        <a-col :span="24">
          <attachment-info
              :params="attachParams"
              typeFrom="bill"
              @getObjectId="getObjectId"
          ></attachment-info>
        </a-col>
      </a-row>
      <a-row class="mt-10" id="operationRecordTurnover">
        <a-col :span="24">
          <a-card title="操作记录">
            <a-table
                :dataSource="optLogList"
                :columns="OPT_LOG_LIST_COLUMNS"
                :pagination="optLogPagination"
                @change="handleOptLogTableChange"
                rowKey="id"
            >
              <template #bodyCell="{ text, record, index, column }">
                <template v-if="column.key === 'operate_content'">
                  {{
                    record.operate_content && record.operate_content.content
                        ? record.operate_content.content
                        : "--"
                  }}
                </template>
              </template>
            </a-table>
          </a-card>
        </a-col>
      </a-row>
    </section>
    <a-modal
        v-model:visible="showModal"
        :title="modalTitle"
        centered
        @cancel="onModalClose"
        @ok="onModalSubmit"
        :width="600"
    >
      <a-textarea
          :placeholder="'请输入' + modalTitle"
          :auto-size="{ minRows: 6 }"
          v-model:value="modalRemarkContent"
      />
    </a-modal>

    <a-modal v-model:visible="visible" title="确认删除流水" @ok="handleOk">
      <div style="margin-bottom: 10px">删除原因</div>
      <div class="box">
        <a-textarea
            v-model:value="value"
            placeholder="输入删除原因"
            :rows="6"
        />
      </div>
    </a-modal>

    <a-modal
        v-model:visible="refundVisible"
        title="确认退款"
        @ok="handleRefundOk"
        :confirmLoading="refundLoading"
    >
      <a-form layout="vertical">
        <a-row :gutter="12">
          <a-col :span="8">
            <a-form-item label="退款金额（元）" v-bind="validateInfos.price">
              <a-input-number
                  style="width: 100%"
                  placeholder="请输入退款金额"
                  v-model:value="refundInfo.price"
                  :min="0.01"
                  :precision="2"
                  :max="Number(detail.nomatch_price)"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="退款原因" v-bind="validateInfos.reason">
              <a-textarea
                  v-model:value="refundInfo.reason"
                  placeholder="输入退款原因"
                  :rows="6"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 匹配账单 -->
    <match-bill
        :cost_type="detail.single_type"
        :visible="billMatchVisible"
        :content="detail"
        @cancel="billMatchVisible = false"
        @success="handleBillMatchSuccess"
    />
    <!-- 取消匹配 -->
    <cancel-match
        :visible="billCancelVisible"
        :content="billContent"
        @cancel="billCancelVisible = false"
        @success="handleMatchCancelSuccess"
    />

    <!-- 账单详情 -->
    <BillDetailDrawer
        :visible="billDetailVisible"
        :id="billDetailId"
        @cancel="
        () => {
          billDetailVisible = false;
        }
      "
        @closeAllModal="closeAllModal"
    />
  </div>
</template>

<script>
import {
  computed,
  defineAsyncComponent,
  defineComponent,
  reactive,
  toRefs,
  watch,
  createVNode,
  ref,
  onUnmounted
} from "vue";
import {useRoute, useRouter} from "vue-router";
import {Form, message, Modal, notification} from "ant-design-vue";
import {
  DisconnectOutlined,
  QuestionCircleOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import utils from "../../../common/utils/utils";
import AttachmentInfo from "../../../components/contract/AttachmentInfo/index.vue";
import MatchBill from "@/views/bill/TurnoverDetail/modules/MatchBill.vue";
import CancelMatch from "@/views/bill/BillDetail/modules/CancelMatch.vue";

const useForm = Form.useForm;
const BillDetailDrawer = defineAsyncComponent(() =>
    import("@/views/bill/BillDetail/modules/BillDetailDrawer.vue")
);
import {TextTip} from "bl-common-vue3";
import store from "@/store";

export default defineComponent({
  name: "turnoverDetail",
  components: {
    AttachmentInfo,
    MatchBill,
    CancelMatch,
    DisconnectOutlined,
    QuestionCircleOutlined,
    BillDetailDrawer,
    PlusOutlined,
    TextTip,
  },
  props: {
    tId: {
      type: [Number, String],
      default: "",
    },
    isDrawer: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, {emit}) {
    const $route = useRoute();
    const $router = useRouter();
    const goBack = () => {
      $router.back();
    };

    const isDrawer =computed(()=>{
      return props.isDrawer || $route.query.isDrawer
    })

    const state = reactive({
      id: Number($route.query.tId || props.tId),
      detail: {},
      //   匹配账单
      showCanceledBill: false,
      billMatchVisible: false,
      matchDisabled: false,
      billList: [],
      billPage: 1,
      billLimit: 10,
      billTotal: 0,
      billContent: {},
      billCancelVisible: false,
      //   附件信息
      attachParams: {
        type: 2,
        source_id: Number($route.query.tId || props.tId),
      },
      //   备注弹窗
      showModal: false,
      modalType: false,
      modalTitle: "",
      modalRemarkContent: "",

      // 操作记录
      optLogPage: 1,
      optLogLimit: 10,
      optLogTotal: 0,
      optLogList: [],
      visible: false,
      value: "",
      // 账单详情
      billDetailVisible: false,
      billDetailId: 0,
      invoice_open: 0, //1 显示按钮
      template_id: 0, //模版id
      billIds: [],
      e_invoce_type: 0, //电子发布类型
      refundVisible: false,
      refundLoading: false,

      receiptAmountAll: 0,
      Pending_approval: false,
      lastClose: -1,


      activeKey: 'flowInfoTurnover',
      tabList: [
        {
          title:'流水信息',
          key: 'flowInfoTurnover'
        },
        {
          title:'匹配账单',
          key: 'matchBillTurnover'
        },
        {
          title:'附件信息',
          key: 'attachmentInfoTurnover'
        },
        {
          title:'操作记录',
          key: 'operationRecordTurnover'
        },
      ],

      // 是否有审批
      processApprove: true,
      Approveis_admin: false,
      Approve_id: 0,
    });

    const refundInfo = reactive({
      reason: "",
      price: "",
    });

    const closeAllModal = () => {
      emit("closeAllModal");
    };

    const refundRule = ref({
      price: [{required: true, message: "退款金额必填"}],
      reason: [{required: true, message: "退款原因必填"}],
    });
    const {resetFields, validate, validateInfos} = useForm(
        refundInfo,
        refundRule
    );

    watch(
        () => props.tId,
        (tId) => {
          if (tId) {
            state.id = Number(tId);
            state.attachParams.source_id = Number(tId);
            init();
          } else {
          }
        }
    );

    const deketed = () => {
      if(state.processApprove){
        state.visible = true;
      }else {
        Modal.confirm({
          title: () => "提示",
          content: () => "您需要先设置删除流水审批流程才能删除流水哦~",
          icon: () => createVNode(ExclamationCircleOutlined),
          centered: true,
          okText: () => "前往",
          onOk() {
            goSetting()
          },
        });
      }
    };

    const goSetting = () => {
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: "审批设置",
              maskCloseable: true,
              visible: true,
              closable: true,
              width: 1200,
              bodyStyle: {padding: 0, background: '#f7f7f7', height: '100%'},
              destroyOnClose: true,
            },
            microId: "approval_ApprovalSettings",
            app: "workApproval",
            url: '/approval/ApprovalSettings',
            params: {
              id: state.Approve_id,
              isMainDrawer: true,
              closeApproval: () => {
                getSetting()
              }
            }
          },

        })
      }

    };

    // 退款
    const refund = () => {
      resetFields();
      state.refundVisible = true;
    };

    // 确认退款
    const handleRefundOk = () => {
      validate().then(() => {
        state.refundLoading = true;
        let params = {
          stream_id: state.id,
          apply_data: {
            nomatch_price: state.detail?.nomatch_price || 0, // 未匹配金额
            remark: refundInfo.reason,
            refund_price: refundInfo.price,
          },
        };
        request.post("/org", "/stream/refundApply", params).then((res) => {
          state.refundLoading = false;
          message.success("退款审批提交成功");
          state.refundVisible = false;
          getTurnoverDetail();
        });
      });
    };

    const handleOk = () => {
      if (!state.value) {
        message.warning("请填写删除原因！");
        return;
      }
      request
          .post("/org", "/bill/deleteStatement", {
            id: state.id,
            reason: state.value,
          })
          .then((res) => {
            message.success("删除流水审批提交成功");
            state.visible = false;
            getTurnoverDetail();
          })
    };

    const getSetting = () => {
      // 获取配置
      request
          .get("/org", "/approval/publish/process", {
            alias: 'delete_statement'
          })
          .then((res) => {
            state.processApprove = res.info.process; //判断是否开启
            state.Approveis_admin = res.info.is_admin; //判断是否有权限
            state.Approve_id = res.info.id;
          });
    };

    const revokes = () => {
      request
          .post("/org", "/bill/cancel", {
            id: state.id,
          })
          .then((res) => {
            message.success("撤销删除流水审批成功");
            // console.log(res)
            getTurnoverDetail();
          });
    };

    const refundCancel = () => {
      request
          .get("/org", "/stream/refundRevoke", {
            stream_id: state.id,
          })
          .then((res) => {
            message.success("撤销退款审批成功");
            getTurnoverDetail();
          });
    };

    // 匹配账单
    const handleBillCancelShowChange = () => {
      state.billPage = 1;
      getMatchBill();
    };
    const handleBillMatchSuccess = () => {
      state.billMatchVisible = false;
      init();
    };
    const handleMatchCancelSuccess = () => {
      state.billCancelVisible = false;
      init();
    };
    const billPagination = computed(() => ({
      total: state.billTotal,
      current: state.billPage,
      pageSize: state.billLimit,
      showSizeChanger: true,
    }));
    const handleBillTableChange = (pager) => {
      state.billPage = pager.current;
      state.billLimit = pager.pageSize;
      getMatchBill();
    };
    const handleBillMatchCancel = (record) => {
      state.billContent = record;
      state.billCancelVisible = true;
    };
    const customBillRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => {
          if (record.bill_id) {
            state.billDetailId = record.bill_id;
            state.billDetailVisible = true;
          }
        },
      };
    };
    const getMatchBill = () => {
      const params = {
        page: state.billPage,
        limit: state.billLimit,
        stream_id: state.id,
      };
      if (state.showCanceledBill) {
        params.match_status = 4;
      }
      request.get("/org", "/stream/getBillList", params).then((res) => {
        state.billList = res.list;
        state.receiptAmountAll = res.list.reduce(
            (accumulator, current) => accumulator + current.receipt_amount,
            0
        );
        state.billTotal = res.total;

        for (let n = 0; n < res.list.length; n++) {
          if (res.list[n].match_status == 6 || res.list[n].match_status == 5) {
            state.Pending_approval = true
          }
        }
      });
    };

    // 附件信息
    const getObjectId = (id) => {
      state.attachParams.object_id = id;
    };

    // 顶部操作按钮
    const handleTopBtnClick = (type) => {
      if (topBtnMap[type].showModal) {
        state.modalTitle = topBtnMap[type].title;
        state.modalType = type;
        state.showModal = true;
      } else {
        topBtnMap[type].submit();
      }
    };
    const onModalSubmit = () => {
      if (!state[topBtnMap[state.modalType].stateKey]) {
        message.warning(`请输入${state.modalTitle}!`);
        return;
      }
      topBtnMap[state.modalType].submit();
    };
    const onModalClose = () => {
      state.showModal = false;
      state[topBtnMap[state.modalType].stateKey] = "";
      state.modalType = "";
      state.modalTitle = "";
    };
    const topBtnMap = {
      close: {
        title: "关闭流水原因",
        showModal: true,
        stateKey: "modalRemarkContent",
        submit: () => {
          request
              .put("/org", "/bill/closeStream", {
                stream_id: state.id,
                needMsg: true,
                close_reason: state.modalRemarkContent,
              })
              .then((res) => {
                message.success(res.msg || "操作成功");
                onModalClose();
                init();
              });
        },
      },
      open: {
        showModal: false,
        submit: () => {
          utils.modalConfirm({
            content: "确认开启当前流水吗？",
            onOk: () => {
              request
                  .get("/org", "/bill/openStream", {
                    stream_id: state.id,
                    needMsg: true,
                  })
                  .then((res) => {
                    message.success(res.msg || "操作成功!");
                    init();
                  });
            },
          });
        },
      },
    };

    let detailTimerl = null;
    const getTurnoverDetail = () => {
      request
          .get("/org", "/bill/streamDetail", {
            stream_id: state.id,
          })
          .then((res) => {
            const {streamDetail} = res;
            state.detail = streamDetail;
            //   流水已经关闭或者完全匹配 则禁掉匹配账单的按钮
            state.matchDisabled = streamDetail.is_close == 0 || streamDetail.is_close == 2 || streamDetail.is_close == 3 || streamDetail.match_status == 1;
            if (streamDetail.object_id) {
              state.attachParams.object_id = streamDetail.object_id;
            }
            state.invoice_open = state.detail.invoice_open;
            state.template_id = state.detail.template_id;
            state.e_invoce_type = state.detail.e_invoce_type;
            state.billIds = state.detail.bill_id_arr;

            if( state.lastClose = 2 && state.detail.is_close != state.lastClose){
              getMatchBill()
            }
            state.lastClose = state.detail.is_close
            if(state.detail.is_close == 2) {
              detailTimerl=  setTimeout(() => {
                getTurnoverDetail()
              }, 3000);
            }
          });
    };

    const getOptLogList = () => {
      request
          .get("/org", "/stream/logList", {
            stream_id: state.id,
            page: state.optLogPage,
            limit: state.optLogLimit,
          })
          .then((res) => {
            state.optLogList = res.list;
            state.optLogTotal = res.total;
          });
    };

    // 操作日志
    const optLogPagination = computed(() => ({
      total: state.optLogTotal,
      current: state.optLogPage,
      pageSize: state.optLogLimit,
      showSizeChanger: true,
    }));

    const handleOptLogTableChange = (pager) => {
      state.optLogPage = pager.current;
      state.optLogLimit = pager.pageSize;
      getOptLogList();
    };

    const OPT_LOG_LIST_COLUMNS = [
      {
        title: "操作人",
        key: "operate_user",
        dataIndex: "operate_user",
      },
      {
        title: "操作内容",
        dataIndex: "operate_content",
        key: "operate_content",
      },
      {
        title: "操作时间",
        key: "operate_time",
        dataIndex: "operate_time",
      },
    ];

    // 开具收据
    const makeInvoice = () => {
      const billIds = state.billIds.join(",");
      const templateid = state.template_id.join(",");
      request
          .post("/org", "/invoice/beforeVerify", {
            billIds: state.billIds,
          })
          .then(() => {
            parent.postMessage(
                {
                  type: "Invoicing",
                },
                "*"
            );

            $router.push({
              name: "makeInvoice",
              query: {
                billIds: billIds,
                e_invoce_type: state.e_invoce_type,
                template_id: templateid,
              },
            });
          })
          .catch((err) => {
            if (err.code >= 50020) {
              if (err.code == 50020 || err.code == 50021) {
                const msg =
                    err.code == 50021
                        ? "费用类型未设置税率信息"
                        : "未配置对应楼宇的发票模板";
                Modal.confirm({
                  title: () => "提示",
                  content: () => err?.msg || `当前账单${msg}，请先前往配置~`,
                  icon: () => createVNode(ExclamationCircleOutlined),
                  centered: true,
                  okText: () => "前往配置",
                  onOk() {
                    parent.postMessage(
                        {
                          type: "Invoicing",
                        },
                        "*"
                    );

                    $router.push({
                      name: "InvoiceSetting",
                      query: {billIds: billIds, type: "template"},
                    });
                  },
                });
              } else if (err.code == 50022) {
                Modal.confirm({
                  title: () => "提示",
                  content: () => `当前账单未匹配适用模板,是否继续进行开票？`,
                  icon: () => createVNode(QuestionCircleOutlined),
                  centered: true,
                  onOk() {
                    parent.postMessage(
                        {
                          type: "Invoicing",
                        },
                        "*"
                    );

                    $router.push({
                      name: "makeInvoice",
                      query: {
                        billIds: billIds,
                        e_invoce_type: state.e_invoce_type,
                        template_id: templateid,
                      },
                    });
                  },
                });
              } else {
                notification.warning({
                  message: "警告",
                  description: err.msg,
                });
              }
            }
          });
    };

    // 开具收据
    const issueReceipts = () => {
      let billIds = [];
      state.billList.forEach((item) => {
        if (
            item.receipt_status == 0 ||
            item.receipt_amount < item.actual_payment
        ) {
          billIds.push(item.bill_id);
        }
      });
      request
          .post("/org", "/receipt/beforeVerify", {
            billIds,
          })
          .then(() => {
            window.microApp.forceDispatch({
              type: "SetChildDrawerList",
              info: {
                props: {
                  title: null,
                  maskCloseable: true,
                  visible: true,
                  closable: false,
                  width: 1200,
                  bodyStyle: {height: '100%',},
                  destroyOnClose: true,
                },
                microId: "org_receipt",
                heightFull: true,
                app: "org",
                url: `/bill/receipt?billIds=${billIds.join(",")}&stream_id=${state.id}&isClose=true`,
                params: {
                  isMainDrawer: true,
                  closeSubmitDrawer: () => {
                    getTurnoverDetail()
                  }
                }
              },
            })
          })
          .catch((err) => {
            if (err.code == 50024) {
              Modal.confirm({
                title: () => "提示",
                content: () =>
                    `当前勾选账单楼宇存在没有配置收据编号生成规则,请先前往配置~`,
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  $router.push({
                    name: "receiptSetting",
                    query: {
                      type: "ruleList",
                    },
                  });
                  emit("closeAllModal");
                },
              });
            }
            if (err.code == 50025) {
              Modal.confirm({
                title: () => "提示",
                content: () =>
                    err.msg || `当前勾选账单楼宇没有配置收款方信息,请先前往配置~`,
                icon: () => createVNode(ExclamationCircleOutlined),
                centered: true,
                okText: () => "前往",
                onOk() {
                  $router.push({
                    name: "receiptSetting",
                    query: {
                      type: "sellerList",
                    },
                  });
                  emit("closeAllModal");
                },
              });
            }
          });
    };

    // 查看收据
    const viewReceipt=()=>{
      window.microApp.forceDispatch({
          type: "SetChildDrawerList",
          info: {
            props: {
              title: null,
              maskCloseable: true,
              visible: true,
              closable: false,
              width: 1200,
              bodyStyle: {height: '100%',},
              destroyOnClose: true,
            },
            microId: "org_receipt_detail",
            heightFull: true,
            app: "org",
            url: `/bill/receiptDetail?group_key=${state.detail.receipt_info.group_key}&isClose=true`,
            params: {
              isMainDrawer: true,
            }
          },
      })
    }

    const init = () => {
      getTurnoverDetail();
      getMatchBill();
      getOptLogList();
      getSetting()
    };

    init();


    // 滚动到指定位置
  let canScroll = true
  let timer = null
  const scrollToAnchor = (key) => {
    canScroll = false
    const element = document.getElementById(key);

    if (element) {
      element.scrollIntoView({ behavior: "smooth" });
      if (!timer) {
        timer =  setTimeout(() => {
          canScroll = true
          timer = null
        }, 500)
      }
    }
  };

  const contentRef = ref(null)

  // 滚动监听选择 activeKey
  const handleScroll =()=>{
    if(!canScroll){
      return
    }
    const containerEl = contentRef.value;
    const scrollTop = containerEl.scrollTop + 20;

    let nearestItem = null;
    let minDistance = Infinity;

    state.tabList.forEach((item) => {
      const itemEl = document.getElementById(`${item.key}`);
      if (!itemEl) return;

      const distance = scrollTop - itemEl.offsetTop;
      if (distance >= 0 && distance < minDistance) {
        minDistance = distance;
        nearestItem = item.key;
      }
    });

    if (nearestItem) {
      state.activeKey = nearestItem;
    }
  }


    

    onUnmounted(() => {
      state.lastClose = -1
      if (detailTimerl) {
        clearTimeout(detailTimerl);
        detailTimerl = null;
      }
    })

    return {
      ...toRefs(state),
      descCols,
      ...descStyle,
      BILL_LIST_COLUMNS,
      billPagination,
      goBack,
      handleTopBtnClick,
      handleBillCancelShowChange,
      handleBillTableChange,
      getObjectId,
      onModalSubmit,
      onModalClose,
      handleBillMatchSuccess,
      customBillRow,
      handleBillMatchCancel,
      handleMatchCancelSuccess,
      OPT_LOG_LIST_COLUMNS,
      optLogPagination,
      handleOptLogTableChange,
      deketed,
      handleOk,
      revokes,
      makeInvoice,
      refund,
      handleRefundOk,
      refundInfo,
      validateInfos,
      refundCancel,
      closeAllModal,
      issueReceipts,
      viewReceipt,
      isDrawer,

      contentRef,
      handleScroll,
      scrollToAnchor,
      getSetting,
      goSetting,
    };
  },
});

const descCols = {xxl: 5, xl: 4, lg: 3, md: 3, sm: 2, xs: 1};
const descStyle = {
  labelStyle: {
    color: "rgba(0,0,0,0.5)",
    fontSize: "12px",
  },
  contentStyle: {
    color: "rgba(0,0,0,0.8)",
    marginBottom: "15px",
    overflow: "hidden",
    paddingRight: "8px",
  },
};
const BILL_LIST_COLUMNS = [
  {
    title: "对方名称",
    key: "company_name",
    dataIndex: "company_name",
  },
  {
    title: "费用类型",
    key: "cost_type_txt",
    dataIndex: "cost_type_txt",
  },
  {
    title: "费用周期",
    key: "period",
    dataIndex: "start_date",
  },
  {
    title: "应收金额",
    key: "price",
    dataIndex: "receivable_payment",
  },
  {
    title: "匹配金额",
    key: "price",
    dataIndex: "match_price",
  },
  {
    title: "匹配日期",
    key: "match_date",
    dataIndex: "match_date",
  },
  {
    title: "取消匹配日期",
    key: "date",
    dataIndex: "cancel_match_date",
  },
  {
    title: "匹配状态",
    key: "match_status_txt",
    dataIndex: "match_status_txt",
  },
  {
    title: "操作",
    key: "action",
    dataIndex: "id",
  },
];
</script>

<style lang="less" scoped>
.turnover-detail {
  height: 100%;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;

  .header {
    position: relative;
    z-index: 99;
    background: #fff;
    padding-bottom: 20px;
    box-shadow: 0px 0px 4px 1px #ddd;

    &:deep(.ant-page-header) {
      border-bottom: 1px dashed #ddd;
    }

    .header-extra {
      .owner-info {
        padding: 0 40px;
        font-size: 20px;
        line-height: 60px;
        font-weight: bold;
        border-bottom: 1px dashed #ddd;
      }

      .owner-padding {
        padding: 0 13px;
      }

      .stais-info {
        padding: 0 40px;
        margin-top: 15px;
      }

      .stais-padding {
        padding: 0 16px;
      }
    }
  }

  .content {
    position: relative;
    z-index: 90;
    flex: 1;
    width: 100%;
    max-height: calc(100% - 210px);
    padding: 10px;
    padding-top: 0px;
    margin-top:10px;
    box-sizing: border-box;
    overflow-y: auto;
  }

  &.back-class {
    :deep(.ant-page-header-back) {
      display: none;
    }

    :deep(.ant-page-header) {
      padding: 16px 7px;
    }
  }

  .hide-back {
    :deep(.ant-page-header-back) {
      display: none;
    }
  }
}

.box {
  textarea {
    resize: none;
  }
}
</style>
